import axios from 'axios'
import Vue from 'vue'
import { message } from 'ant-design-vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const baseUrl = process.env.VUE_APP_API_BASE_URL
export function apiDownload (fileName, needDelete) {
  var url = baseUrl + '/common/download'
  return axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
    params: {
      fileName,
      delete: needDelete
    }
  }).then(res => {
    resolveBlob(res)
  })
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob (res) {
  console.log(res)
  const contentType = decodeURI(res.headers['content-type'])
  // 如果 content-type 为 application/json 说明下载失败
  if (contentType.indexOf('application/json') !== -1) {
    const reader = new FileReader()
    let result = {}
    reader.readAsText(res.data, 'utf-8')
    reader.onload = () => {
      result = JSON.parse(reader.result)
      console.log(result)
      message.error('下载失败，原因：' + result.message || '未知')
    }
    return
  }
  const aLink = document.createElement('a')
  const blob = new Blob([res.data])
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  const contentDisposition = decodeURI(res.headers['content-disposition'])
  const result = patt.exec(contentDisposition)
  let fileName = result[1]
  fileName = fileName.replace(/"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}
